$(function(){
    var name,
        score = 0,
        time = 100,
        timer = null,
        index = 0,
        current = $('#problem').attr('d');

    while(!name){
        name = prompt('请输入你的名字：');
        if(name) $('.test_name span').text(name);
    }

    timer = setInterval(function(){
        --time;
        time ? update() : end();
        if ( index == 5 ) end();
    }, 1000);

    $('#workspace').click(() => {
        setTimeout(function(){
            if( current != $('#problem').attr('d') || !$('#stage_score').attr('class') ) {
                ++index;
                score < 100 ? score += 20 : score;
                update();
                current = $('#problem').attr('d');
                if(score == 100) $('.text_win').css('display','block');
            }
        },600)
    });
  
    function update(){
        $('.test_score span').text(score);
        $('.test_time span').text(time);
        $('.test_end').text(`姓名：${name}, 成绩：${score}, 用时：${100 - time}'S`);
    }

    function end(){
        clearInterval(timer);
        update();
        if( index != 5 ) alert(`测试结束，姓名：${name}, 成绩：${score}, 用时：${100 - time}'S`);
        $.ajax({
            url: './php/save.php',
            type: 'POST',
            data: {
                name,
                time: 100 - time,
                score,
                status: index == 5 ? '1' : '0',
            }
        });
    }
})